package lib

import (
	"GameServer/Common/utils"
	"GameServer/Game/errors"
	"GameServer/Game/m"
	"GameServer/Game/sp"
	"GameServer/Game/union"
	"fmt"
	"sort"

	"GameServer/Common/data"

	"github.com/globalsign/mgo/bson"
)

func UnionCreate(u *m.User, req *sp.CreateUnionRequest) (uProp *m.UpdateProp, unionInfo *m.Union, members map[string]*m.UnionMember, err error) {
	// @todo 创建公会扣钱
	itemCost := m.BaseKV{Key: data.GlobalEnum.Diamond, Val: data.UnionConstEnum.CreateCost}

	uProp, err = Cost("UnionCreate", u, []m.BaseKV{itemCost})
	if err != nil {
		return
	}
	unionInfo, members, err = union.UnionModule.CreateUnion(u, req)
	if err != nil {
		return
	}
	return
}

func UnionRecvEnergy(u *m.User, uEnergy *m.UnionEnergy, recv *m.UnionEnergyRecv, PSend func(interface{}) error) (uProp *m.UpdateProp, err error) {
	if len(uEnergy.Recvs) >= 5 {
		err = errors.New("已经获取到5点体力")
		return
	}
	uProp, _, _, err = GiveGoodsByKv("UnionRecvEnergy", u, m.BaseKV{Key: data.GlobalEnum.Energy, Val: recv.EnergyNum}, PSend)
	if err != nil {
		return
	}
	uEnergy.AddRecv(recv)
	return
}

// 处理公会签到信息
func HandleUnionSignIn(us *m.User) (endTime int64, integral int64, surplus int64, err error) {
	now := utils.TNow()
	nowUnix := now.Unix()
	// 1、当前时间 等于 公会当前签到时间 不需要做任何处理
	// 2、当前时间 不等于 公会当前签到时间
	if !utils.IsSameDay(nowUnix, us.UnionCurTime) {
		tplLst, ok := data.GetAllDatas("UnionSignIns")
		if !ok {
			err = errors.NewErrcode(data.Errcode.ConfigNotFound, "找不到UnionSignIns配置表")
			return
		}
		// 更新工会当前签到时间
		us.UnionCurTime = utils.ZeroTime(now)
		// 加入公会已经几天了
		jionDay := (us.UnionCurTime-us.UnionJionTime)/86400 + 1
		sort.Slice(tplLst, func(i, j int) bool {
			ai := tplLst[i].(data.UnionSignIn)
			aj := tplLst[j].(data.UnionSignIn)
			return ai.Id < aj.Id
		})

		length := len(tplLst)
		idx := 0
		if jionDay <= int64(length) {
			idx = int(jionDay - 1)
		} else { // 超过天数，取最后一次数据
			idx = length - 1
		}
		tplT := tplLst[idx].(data.UnionSignIn)

		us.UnionSignNum = int64(tplT.Num)
		us.UnionIntegral = int64(tplT.Integral)
		us.Update(us)
	}

	endTime = us.UnionCurTime + 86400
	integral = us.UnionIntegral
	surplus = us.UnionSignNum
	return
}

// 工会签到领取积分奖励
func GetIntegral(from string, us *m.User, PSend func(interface{}) error) (uProp *m.UpdateProp, endTime int64, integral int64, surplus int64, err error) {
	now := utils.TNow()
	nowUnix := now.Unix()
	// 当前时间 不等于 公会积分时间 说明工会积分时间没有刷新
	if !utils.IsSameDay(us.UnionCurTime, nowUnix) {
		err = errors.NewErrcode(data.Errcode.ServerErr, fmt.Sprintf("公会当前时间%d", us.UnionCurTime))
		return
	}
	// 当前剩余领取次数0
	if us.UnionSignNum <= 0 {
		err = errors.NewErrcode(data.Errcode.ServerErr, fmt.Sprintf("当前剩余领取次数%d", us.UnionSignNum))
		return
	}
	// 给玩家发送积分
	uProp, _, _, err = GiveGoodsByKv(from, us, m.BaseKV{Key: data.GlobalEnum.Union, Val: us.UnionIntegral}, PSend)
	if err != nil {
		return
	}
	// 领取公会积分成功，减少领取剩余次数
	us.UnionSignNum--
	us.Update(us)

	endTime = us.UnionCurTime + 86400
	integral = us.UnionIntegral
	surplus = us.UnionSignNum
	return
}

// 设置公会积分天数
func SetUnionSignInDay(us *m.User, day int64) {
	now := utils.TNow()
	// 获取当前时间的凌晨时间戳
	nowZeroTime := utils.ZeroTime(now)
	// 重置加入公会时间
	// 加入公会时间=当前凌晨时间+(天数-1)*一天的秒数
	us.UnionJionTime = nowZeroTime + (day-1)*86400
	us.UnionCurTime = nowZeroTime - 86400

	HandleUnionSignIn(us)
}

// 重置玩家红包信息
func HandleRedPacket(us *m.User) (redPacket *m.UnionRedPacket, err error) {
	redPacket = m.GetUnionRedPacket(us.Uid.Hex())

	tplLst, ok := data.Filters("ActPaidProps", func(val interface{}) bool {
		valT := val.(data.ActPaidProp)
		return int64(valT.PackTyp) == data.PaidPropsEnum.ShareBagPack
	})
	if !ok {
		err = errors.NewErrcode(data.Errcode.ConfigNotFound, "没有找到该配置表的数据ActPaidProps")
		return
	}
	nowUnix := utils.TNow().Unix()
	cnt := 0
	for _, item := range tplLst {
		itemT := item.(data.ActPaidProp)
		bTime, _ := utils.LayoutToTime(itemT.BeginTime)
		eTime, _ := utils.LayoutToTime(itemT.EndTime)
		if nowUnix < bTime.Unix() || eTime.Unix() < nowUnix {
			cnt++
		}
	}
	// 所有分享活动都关闭了，清理玩家身上的红包
	if cnt == len(tplLst) {
		if redPacket.SendRedPacket != nil && len(redPacket.SendRedPacket) > 0 {
			unionId := bson.ObjectIdHex(us.UnionId)
			// 删除旧的红包消息
			for _, item := range redPacket.SendRedPacket {
				m.DeleteUnionChatMsg(unionId, item.Uid, item.Mid)
			}
			// 清理自身的红包
			redPacket.Clear()
		}
	}
	return
}

// 获取红包中的道具
func GetRedPacketGoods(packId int64) (r []m.BaseKV, err error) {
	r = make([]m.BaseKV, 0)
	tpl, ok := data.Get("ShareBagPacks", uint64(packId))
	if !ok {
		err = errors.NewErrcode(data.Errcode.ConfigNotFound, "没有找到配表ShareBagPacks，或者没有数据")
		return
	}
	tplT := tpl.(data.ShareBagPack)
	for _, item := range tplT.Goods {
		r = append(r, m.BaseKV{
			Key: int64(item.Key),
			Val: int64(item.Value),
		})
	}
	return
}

// 查找公会聊天信息
func FindChatMsg(us *m.User, tuid string, mid string) (msgChat *m.ChatMsg, err error) {
	lst, err := m.NewUnionChatMsg(us.UnionId).GetMsgList()
	for _, item := range lst {
		if item.Mid == mid && item.Uid == tuid {
			return item, nil
		}
	}
	err = errors.NewErrcode(data.Errcode.ServerErr, "没有该消息")
	return
}
